<template>
  <div class="user-edit mtop-20">
    <div class="font-20 font-bold">编辑个人信息</div>
    <div class="edit-wrap mtop-20">
      <el-form class="edit-form" :model="form" label-width="80px" size="mini">
        <el-form-item label="昵称：">
          <el-input v-model="form.nickname"></el-input>
        </el-form-item>
        <el-form-item label="介绍：">
          <el-input type="textarea" maxlength="100" show-word-limit v-model="form.signature"></el-input>
        </el-form-item>
        <el-form-item label="性别：">
          <el-radio-group v-model="form.gender">
            <el-radio-button :label="0">保密</el-radio-button>
            <el-radio-button :label="1">男</el-radio-button>
            <el-radio-button :label="2">女</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日：">
          <el-date-picker v-model="form.birthday" type="date" placeholder="选择日期" :editable="false">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div class="edit-img-container">
        <ImgCut btnText="修改头像" :imgUrl="imgUrl" @upload="upload" />
      </div>
    </div>
    <div class="submit-wrap">
      <button class="btn btn-blue" @click="update" :disabled="!form.nickname">
        保存
      </button>
      <button class="btn btn-white" @click="$router.back()">取消</button>
    </div>
  </div>
</template>

<script>
import { updateUserInfo, uploadAvatar, getUserDetail } from "@/api/api_user";
import ImgCut from "@/components/img-cut/ImgCut";
import { mapState } from "vuex";
import dayjs from "dayjs";
export default {
  components: {
    ImgCut,
  },
  data() {
    return {
      form: {
        nickname: "",
        signature: "",
        gender: 0,
        birthday: "",
      },
    };
  },
  computed: {
    ...mapState(["profile"]),
    imgUrl() {
      return this.profile.photoPath
        ? this.profile.photoPath
        : require("../../assets/img/avatar.jpeg");
    },
  },
  created() {
    this.getInfo();
  },
  methods: {
    getInfo() {
      const userInfo =
        Object.keys(this.profile).length !== 0
          ? this.profile
          : JSON.parse(localStorage.getItem("profile"));
      if (Object.keys(userInfo).length !== 0) {
        const { nickname, signature, gender, birthday, photoPath } = userInfo;
        this.form = {
          nickname,
          signature,
          gender: gender === null ? 0 : gender,
          birthday: birthday
            ? dayjs(birthday).format("YYYY-MM-DD")
            : new Date(),
          photoPath,
        };
        this.profile.photoPath = photoPath;
      }
    },
    /* 上传头像 */
    async upload({ file }) {//TODO:这里上传图片有点小问题！！！！
      if ((file.size / Math.pow(1024.0, 2)).toFixed(2) > 1) {
        this.$message.warning("图片大小请小于 1024KB");
        return;
      }
      const formData = new FormData();
      formData.append(
        "file",
        new File([file], `userAvatar.${file.type.split("/")[1]}`, {
          type: file.type,
        })
      );
      const imgObj = {
        token: localStorage.getItem("token"),
        file: formData,
      };

      const res = await uploadAvatar(imgObj);
      if (res.data.code !== 200) return this.$message.error("上传失败");
      this.$message.success("上传成功");
      this.getUserDetail();
    },
    async getUserDetail() {
      const token = localStorage.getItem("token");
      const res = await getUserDetail(token);
      if (res.status !== 200) return;
      if (res.data.data) {
        // const host = `${window.location.origin}/mock`
        const data = {
          ...res.data.data,
          // photoPath: `${host}/${res.data.photoPath}`
          photoPath: `${res.data.data.photoPath}`,
        };
        //下面的这个信息是正确的
        this.$store.commit("setProfile", data);//这里设置了头像信息！！！
      }
    },
    async update() {
      const params = {
        token: localStorage.getItem("token"),
        nickname: this.form.nickname,
        signature: this.form.signature,
        gender: this.form.gender.toString(),
        birthday: dayjs(this.form.birthday).format("YYYYMMDD"),
      };
      const res = await updateUserInfo(params);
      
      if (res.data.code !== 200) return this.$message.error("更新失败");
      this.$message.success("更新成功");
      this.$store.commit("setProfile", {//在state中存入的简单数据，一个对象
        nickname: this.form.nickname,
        signature: this.form.signature,
        gender: this.form.gender.toString(),
        birthday: this.form.birthday,
      });

      this.$router.back();
    },
  },
};
</script>

<style lang="less" scoped>
.edit-form {
  width: 500px;

  @media screen and (max-width: 415px) {
    width: auto;
  }
}

.edit-wrap {
  display: flex;

  @media screen and (max-width: 415px) {
    display: block;
  }
}

.edit-img-container {
  margin-left: 30px;

  @media screen and (max-width: 415px) {
    margin: 0;
  }
}

.submit-wrap {
  margin: 10px 0 0 80px;

  .btn {
    width: 80px;

    &:nth-child(2) {
      margin-left: 20px;
    }
  }
}
</style>
